#!/usr/bin/env python
# -*- coding: utf-8 -*-
#本代码来自所出售产品的淘宝店店主编写
#未经受权不得复制转发
#淘宝店：https://fengmm521.taobao.com/
#再次感谢你购买本店产品
import os,sys
import serial
import time
import json
import cmdUtil
import pathtool
import random


from sys import version_info  

isTest = False

SERIALOBJ = None


# type2Pins[1]   # ['0','1']
# type2Pins[1][0] # '0'
#获取当前python版本
def pythonVersion():
    return version_info.major

def delayT(t):
    for i in range(t):
        time.sleep(1)
        print(t-i)

def readcom():
    n = SERIALOBJ.inWaiting()
    while n<=0:
        time.sleep(0.01)
        n = SERIALOBJ.inWaiting()
    pstr = SERIALOBJ.read(n)
    dstr = ''
    if pythonVersion() > 2:
        dstr = pstr.decode()
        print('main_recive1:',dstr)
    else:
        dstr = pstr
        print('main_recive2:',dstr)
    return dstr

def readcomFirst():
    n = SERIALOBJ.inWaiting()
    if n > 0:
        pstr = SERIALOBJ.read(n)
        if pythonVersion() > 2:
            print(pstr.decode())
        else:
            print(pstr)

def sendcmd(cmd):
    sendstr = cmd + '\n'
    print('main send:',sendstr)
    if pythonVersion() > 2:
        s = SERIALOBJ.write(sendstr.encode())
    else:
        s = SERIALOBJ.write(sendstr.encode())
    SERIALOBJ.flush()

def sendAndread(v):
    sendcmd(v)
    time.sleep(0.05)
    return readcom()

def readconfig():
    f= open('config.txt','r')
    jstr = f.read()
    f.close()
    devdic = json.loads(jstr)
    return devdic['port']
def readData():
    f = open('data.txt','r')
    dat = f.read()
    f.close()
    dat = dat.replace('\n','').replace('\r','').replace(' ','').replace('\t','')
    return dat


def getPConfig():
    f = open('data.txt','r')
    pdat = f.read().replace(' ','').replace('\t','').replace('\n','').replace('\r','')
    f.close()
    return pdat

def delayT(t):
    for i in range(t):
        time.sleep(1)
        print(t-i)

f = open('time.txt','r')
dattimetmp = f.read().replace(' ','').replace('\t','').replace('\n','').replace('\r','')
f.close()

sdtimes = dattimetmp.split(',')

sdelaytims = [int(sdtimes[0]),int(sdtimes[1])]



sendDelay = float(random.randint(sdelaytims[0],sdelaytims[1]))/1000.0   #发送数据间隔时间,单位:秒

def updateSendDelay():
    global sendDelay
    sendDelay = float(random.randint(sdelaytims[0],sdelaytims[1]))/1000.0   #发送数据间隔时间,单位:秒

mMac = ''

def findAllDevicesName():
    alldict = cmdUtil.allDevices()
    for k,v in alldict.items():
        if k.find(mMac) != -1:
            n = k.split('-')[0]
            return n
    return None
def saveMacAaddr(mac):
    nMacName = mMac
    ntmp = findAllDevicesName()
    if ntmp:
        nMacName = mMac
    localAllDevices = []
    newDirpth = pathtool.cur_file_dir() + os.sep + 'newDevices' + os.sep + nMacName + '.txt'
    runDirpth = pathtool.cur_file_dir() + os.sep + 'runDevices' + os.sep + nMacName + '.txt'
    setDirpth = pathtool.cur_file_dir() + os.sep + 'setDevices' + os.sep + nMacName + '.txt'
    if os.path.exists(newDirpth):
        f = open(newDirpth,'r')
        dat = f.read().replace(' ','').replace('\t','').replace('\r','')
        lines = dat.split('\n')
        for i,v in enumerate(lines):
            tmpmac = v.split(',')[1]
            localAllDevices.append(tmpmac)
    if mac in localAllDevices:
        print('the mac addr did in newDevices')
        newlocalAllDevices = list(set(localAllDevices))
        if len(newlocalAllDevices) != len(localAllDevices):
            outstr = ''
            for i,v in enumerate(newlocalAllDevices):
                outstr += str(i+1) + ',' + v + '\n'
                print(v)
            f = open(newDirpth,'w')
            f.write(outstr[:-1])
            f.close()
            f = open(runDirpth,'w')
            f.write(outstr[:-1])
            f.close()
            f = open(setDirpth,'w')
            f.write(outstr[:-1])
            f.close()
        return
    else:
        localAllDevices.append(mac)
        outstr = ''
        localAllDevices = list(set(localAllDevices))
        for i,v in enumerate(localAllDevices):
            outstr += str(i+1) + ',' + v + '\n'
            print(v)
        f = open(newDirpth,'w')
        f.write(outstr[:-1])
        f.close()
        f = open(runDirpth,'w')
        f.write(outstr[:-1])
        f.close()
        f = open(setDirpth,'w')
        f.write(outstr[:-1])
        f.close()
        return

def testMacMsg(dat):
    datx = dat.replace(' ','').replace('\r','').replace('\n','').replace('\t','')
    dats = datx.split('-')
    if len(dats) != 2:
        print('data erro:',dats)
        return 
    d1 = dats[0]
    d2tmp = dats[1]
    d2 = d2tmp.replace(':','')
    if d1[3:] == d2[3:]:
        print('save mac addr to newDevices dir')
        saveMacAaddr(d2tmp)
    else:
        print(d1,len(d1))
        print(d2,len(d2))
        print('dats is not one mac addr:',dats)

def main(cmd):
    global SERIALOBJ,mMac
    print('使用config.txt配置文件中的串口设置')
    dev = readconfig()
    btv = 115200                        #得到波特率
    if dev:
        print('port:' + dev)
        print('btv:' + str(btv))
    else:
        print('com init erro')
        return  
    SERIALOBJ = serial.Serial(dev,btv,timeout=1)
    if SERIALOBJ:
        print(SERIALOBJ.name)               #串口名
        print(SERIALOBJ.port)               #串口号
        print(SERIALOBJ.baudrate)           #波特率
        print(SERIALOBJ.bytesize)           #字节大小
        print(SERIALOBJ.parity)             #校验位N－无校验，E－偶校验，O－奇校验
        print(SERIALOBJ.stopbits)           #停止位
        print(SERIALOBJ.timeout)            #读超时设置
        print(SERIALOBJ.writeTimeout)       #写超时
        print(SERIALOBJ.xonxoff)            #软件流控
        print(SERIALOBJ.rtscts)             #硬件流控
        print(SERIALOBJ.dsrdtr)             #硬件流控
        print(SERIALOBJ.interCharTimeout)   #字符间隔超时
        print('-'*10)
        time.sleep(1)
        readcomFirst()
        mMac = sendAndread('t')
        mMac = mMac.replace(':','').replace(' ','').replace('\r','').replace('\n','').replace('\t','')
        print(mMac)
        if not mMac:
            print('devices mac erro:%s'%(mMac))
            SERIALOBJ.close()
            SERIALOBJ = None
            return
        delayT(3)
        if cmd == 1:    #设置
            devdict = cmdUtil.setDevices()
            print(devdict)
            for k,v in devdict.items():
                kmac = k
                if kmac.find('-') != -1:
                    kmac = k.split('-')[1]
                if kmac == mMac:
                    cmacs = v
                    pdat = getPConfig()
                    for i,v in enumerate(cmacs):
                        cmac = v.split(',')[1]
                        sendcmd = cmac + '-p' + pdat
                        print(sendcmd)
                        rcmd = sendAndread(sendcmd)
                        if rcmd == sendcmd:
                            print('send set data ok...')
                        time.sleep(sendDelay)
        elif cmd == 2:  #启动
            devdict = cmdUtil.startDevices()
            for k,v in devdict.items():
                kmac = k
                if kmac.find('-') != -1:
                    kmac = k.split('-')[1]
                print('kmac',kmac,mMac)
                if kmac == mMac:
                    cmacs = v
                    for i,v in enumerate(cmacs):
                        cmac = v.split(',')[1]
                        sendcmd = cmac + '-s'
                        sendAndread(sendcmd)
                        updateSendDelay()
                        print(sendDelay)
                        time.sleep(sendDelay)
        elif cmd == 3:  #停止
            devdict = cmdUtil.startDevices()
            for k,v in devdict.items():
                kmac = k
                if kmac == mMac:
                    cmacs = v
                    for i,v in enumerate(cmacs):
                        cmac = v.split(',')[1]
                        sendcmd = cmac + '-e'
                        print(sendcmd)
                        sendAndread(sendcmd)
                        time.sleep(sendDelay)
        else:
            while True:
                dat = readcom()
                testMacMsg(dat)
                time.sleep(0.01)
        delayT(3)
        SERIALOBJ.close()
        SERIALOBJ = None
    else:
        print('串口不存在')


if __name__ == '__main__':
    args = sys.argv
    fpth = ''
    if len(args) == 2 :
        main(int(args[1]))
    else:
        main(0)